/*
 * servidor.c
 *
 *  Created on: 30/10/2011
 *      Author: agustin
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include "Protocolo_NIPC.h"

#define DIRECCION_IP "192.168.1.105"

typedef struct Persona {
	char nombre[50];
	char apellido [50];
}t_persona;

typedef t_persona *persona;



 int main(int argc, char **argv)
{

int server_sockfd;
unsigned int server_len, client_sockfd;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
char c[1024];

/* Crear un socket para el server */

server_sockfd = socket(AF_INET, SOCK_STREAM, 0);



/* nombre del socket */
memset(&server_address,0,sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr(DIRECCION_IP) ;
server_address.sin_port = 2727;
server_len = sizeof(server_address) ;
bind(server_sockfd, (struct sockaddr *)&server_address, server_len) ;
listen(server_sockfd, 1);
printf("listen\n");

int n;
unsigned int client_len;
client_len=sizeof(client_address);

client_sockfd=accept(server_sockfd,(struct sockaddr *)&client_address, &client_len);
printf("Connected\n");
char str[515]="jaite";
char string[515];
/*t_persona *persona;
persona=(t_persona*)malloc(sizeof(t_persona)); */
//paquete *NIPC;
//NIPC=(paquete*)malloc(sizeof(paquete));
paquete *paquete_R_NIPC;
paquete_R_NIPC = (paquete*)malloc(sizeof(paquete));
n = recv(client_sockfd, paquete_R_NIPC,sizeof(paquete), 0);
int resultado_handshake;
/*printf("recibi bien\n");
handshakePRAID_PPD(client_sockfd, paquete_R_NIPC); */

if (n <= 0) {
		     if (n < 0)
			 perror("recv");
			 exit(1);
		     }
printf("%i\n",paquete_R_NIPC->type);
printf("%i\n",paquete_R_NIPC->payload_Length);
printf("%s\n",paquete_R_NIPC->payload);
/* printf("%s\n",persona->nombre);
 printf("%s\n",string);
if(string[0]=='f'){send(client_sockfd,str,strlen(str),0);} */ // ESTO ESTA BIEN
resultado_handshake=handshakePRAID_PPD(client_sockfd,paquete_R_NIPC);
	if (resultado_handshake==1) {
		printf("Salio bien la operacion\n");
	}
	else {
		printf("Salio mal la operacion\n");
		close(client_sockfd);
	}






close(server_sockfd);
return 0;
}
